﻿namespace Sai.Core.Reporting
{
	using System;
	using System.IO;

	public class FileBasedReportStyler : IReportStyler
	{
		private readonly string DefaultHeadTagFile = "headtag.txt";
		private readonly string DefaultStyleTagFile = "styletag.txt";
		private readonly string DefaultHeadingFile = "heading.txt";
		private readonly string DefaultFooterFile = "footer.txt";

		public FileBasedReportStyler(string folder)
		{
			if (string.IsNullOrEmpty(folder))
				throw new ArgumentNullException();

			this.HeadTag = LoadIfExists(folder, DefaultHeadTagFile);
			this.StyleTag = LoadIfExists(folder, DefaultStyleTagFile);
			this.HeadingText = LoadIfExists(folder, DefaultHeadingFile);
			this.FooterText = LoadIfExists(folder, DefaultFooterFile);
		}

		public string HeadTag
		{
			get;
			set;
		}

		public string StyleTag
		{
			get;
			set;
		}

		public string HeadingText
		{
			get;
			set;
		}

		public string FooterText
		{
			get;
			set;
		}

		public bool IsValid
		{
			get
			{
				// we need at least one of these items to be supplied...
				return !string.IsNullOrEmpty(this.HeadTag)
					|| !string.IsNullOrEmpty(this.StyleTag)
					|| !string.IsNullOrEmpty(this.HeadingText)
					|| !string.IsNullOrEmpty(this.FooterText);
			}
		}

		private string LoadIfExists(string folder, string fileName)
		{
			string path = Path.Combine(folder, fileName);

			if (File.Exists(path))
			{
				using (TextReader reader = new StreamReader(path))
				{
					return reader.ReadToEnd();
				}
			}

			return string.Empty;
		}
	}
}
